<?php
/**
 * 
 * 通用货币类 - 用于游戏筹码
 * 注：非社区金币(Money)
 * @author will
 *
 */
class Currency {
	private static function getTableName($type) {
		return $type . '_currency';
	}
	
	/**
	 * 获取货币数据
	 * @param <string> $type
	 * @param <int> $uin
	 * @param <string> $col
	 */
	public static function get($type , $uin , $col = 'currency') {
		$table_name = self::getTableName($type);
		
		$Db = loadDB();
		$result = $Db->getOne("SELECT * FROM `{$table_name}` WHERE `uin` = " . $uin);
		
		// 如果金库数据不存在，则新写入一条数据
		if($result === false) {
			$query_data = array(
				'uin' => $uin,
				'currency' => 0,
				'time' => 0,
			);
			$Db->doInsert($table_name , $query_data);
			
			$result = $query_data;
		}
		
		return $col == 'all' ? $result : $result[$col];
	}
	
	/**
	 * 修改货币
	 * @param <string> $type
	 * @param <int> $uin
	 * @param <int> $num
	 */
	public static function update($type , $uin , $num) {
		$table_name = self::getTableName($type);
		
		$Db = loadDB();
		
		$currency = self::get($type , $uin , 'currency');
		$next_num = $currency + $num;

		if($next_num < 0) {
			$next_num = 0;
		}
		
		$query_data = array(
			'currency' => $next_num,
			'time' => isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time(),
		);
		
		$success = $Db->doUpdate($table_name , $query_data , "`uin` = {$uin}");
		
		return $success ? 0 : 801;
	} 
	
	/**
	 * 获取排行榜 (慎用，currency 没有索引，最好用于定时脚本)
	 * @param <string> $type
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	public static function getTopList($type , $offset = 0 , $limit = 10) {
		$table_name = self::getTableName($type);
		
		$Db = loadDB();
		
		$result = $Db->getAll("SELECT `uin` , `currency` FROM `{$table_name}` ORDER BY `currency` DESC LIMIT {$offset} , {$limit}");
		return $result;
	}
}

# end of script
